package com.yungam.imcs.controller.person;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yungam.common.bean.menu.RolePermission;
import com.yungam.common.bean.role.Role;
import com.yungam.common.bean.user.User;
import com.yungam.common.response.RetDTO;
import com.yungam.common.service.RolePermissionService;
import com.yungam.common.service.RoleService;
import com.yungam.common.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

@Api(tags = "角色管理页面接口")
@RestController
@RequestMapping("/roles")
public class RoleController {

    @Resource
    private RoleService service;
    @Resource
    private RolePermissionService permissionService;
    @Resource
    private UserService userService;

    @ApiOperation("获取所有角色信息")
    @GetMapping("/role")
    public RetDTO<?> getRoles() {
        QueryWrapper<Role> qw = new QueryWrapper<>();
        qw.orderByDesc("create_time"); // 查询所有角色信息
        return RetDTO.data(service.list(qw));
    }

    @ApiOperation("删除某一角色")
    @DeleteMapping("/role")
    public RetDTO<?> delOneRole(@ApiParam("角色 id") Integer id) {
        service.removeById(id);
        // 删除角色的同时, 也要清空角色所属的菜单信息, 即根据 role_id 清空 `role_permission` 表
        QueryWrapper<RolePermission> qw = new QueryWrapper<>();
        qw.eq("role_id", id);
        permissionService.remove(qw);
        // 清空用户是该角色`id`的`role_id`字段
        UpdateWrapper<User> uuw = new UpdateWrapper<>();
        uuw.eq("role_id", id).set("role_id", null);
        userService.update(uuw);
        return RetDTO.success();
    }

    @ApiOperation("添加角色")
    @PostMapping("/role")
    public RetDTO<?> addRole(@ApiParam("角色实体") @RequestBody Role role) {
        // 查重
        QueryWrapper<Role> qw = new QueryWrapper<>();
        qw.eq("role_name", role.getRoleName());
        if (service.getOne(qw) != null) return RetDTO.error("该角色名称已存在");
        role.setCreateTime(new Date());
        service.save(role);
        return RetDTO.success();
    }

    @ApiOperation("修改角色")
    @PutMapping("/role")
    public RetDTO<?> updateRole(@ApiParam("角色实体") @RequestBody Role role) {
        // 判断角色名称是否改变, 如果改变则需要查重
        Role old = service.getById(role.getId());
        if (!Objects.equals(old.getRoleName(), role.getRoleName())) { // 查重
            QueryWrapper<Role> qw = new QueryWrapper<>();
            qw.eq("role_name", role.getRoleName());
            if (service.getOne(qw) != null) return RetDTO.error("该角色名称已存在");
        }
        service.updateById(role);
        return RetDTO.success();
    }
}
